package com.hzdp.web.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {

	public static String getCookie(HttpServletRequest request, String name) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(name)) {
					return cookie.getValue();
				}
			}
		}
		return null;
	}

	public static void setCookie(HttpServletResponse response, String name, String value) {
		Cookie cookie = new Cookie(name, value);
		response.addCookie(cookie);
	}

	public static void setRootCookie(HttpServletRequest request, HttpServletResponse response, String name, String value) {
		String path = getRootPath(request);
		setCookie(response, name, value, path);
	}

	private static String getRootPath(HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		String path = null;
		int indexOf = requestURI.indexOf("/", 1);
		if (indexOf != -1) {
			path = requestURI.substring(0, indexOf);
		} else {
			path = "/";
		}
		return path;
	}

	public static void setCookie(HttpServletResponse response, String name, String value, String path) {
		Cookie cookie = new Cookie(name, value);
		cookie.setPath(path);
		response.addCookie(cookie);
	}

	public static void setCookie(HttpServletResponse response, String name, String value, int maxAge) {
		Cookie cookie = new Cookie(name, value);
		cookie.setMaxAge(maxAge);
		response.addCookie(cookie);
	}
	
	public static void setRootCookie(HttpServletRequest request,HttpServletResponse response, String name, String value, int maxAge) {
		String path = getRootPath(request);
		Cookie cookie = new Cookie(name, value);
		cookie.setPath(path);
		cookie.setMaxAge(maxAge);
		response.addCookie(cookie);
	}
}
